#!/bin/bash

# README SIMPLE START----------------------------
# author: xuGenYin
# date: 2023-08-20
# softList: cVersion,mysql8.0,jdk1.8,jdk11,maven3.8,docker20.10,redis7.0,mongoDb5.0.20,nacos1.4.3,rockerMq5.11 rockerMqDb1.1
# desc: how to use? what want to use, open what in mainFun
# THIS SH SYSTEM IS FOR UBUNTU 20.04
# 1.安装前请先配置好网络
# 2.尽量使用阿里APT源
# 3.本shell尚未做到完全可控---使用时请注意变量与路径---
# README SIMPLE END----------------------------


# ----------资源位置
readonly resLocationPackage="/usr/local/package"
readonly resLocationFile="/usr/local/"

# TODO:----------日志文件
readonly initVersion="/ideaUser/initVersion.txt"
readonly bugLog="/ideaUser/bug.log"

# ----------scp拉取的远程服务器
readonly remotePasswd="xxx"
readonly remoteFileLocation="/home/monolith/Documents"
readonly remoteMachine="xxx"

# ----------指定mysql信息
readonly mysqlBaseVersion="mysql-server_8.0.20-2ubuntu20.04_amd64.deb-bundle.tar"
readonly mysqlUrl="https://downloads.mysql.com/archives/get/p/23/file/${mysqlBaseVersion}"
# 设置MySql的root用户的密码
root_password="xxx"

# ----------指定jdk1.8信息
readonly jdk1_8Version="openjdk-8u41-b04-linux-x64-14_jan_2020"
readonly jdk1_8BaseVersionSuffix="$jdk1_8Version.tar.gz"
readonly jdk8Url="https://download.java.net/openjdk/jdk8u41/ri/$jdk1_8BaseVersionSuffix"

# ---------指定jdk11信息
readonly JDKVersion="jdk-11.0.2"
readonly jdk11BaseVersion="openjdk-11.0.2_linux-x64_bin.tar.gz"
readonly jdk11Url="https://download.java.net/java/GA/jdk11/9/GPL/${jdk11BaseVersion}"


# ---------指定maven信息
readonly mavenVersion="maven3.8.8.tar.gz"

# ---------指定Docker信息
readonly dockerContainerd="https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/containerd.io_1.4.12-1_amd64.deb"
readonly dockerCeCli="https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_20.10.12~3-0~ubuntu-focal_amd64.deb"
readonly dockerCe="https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce_20.10.12~3-0~ubuntu-focal_amd64.deb"
readonly dockerConfigUrl="https://ecb7jimb.mirror.aliyuncs.com"

# ---------指定DockerCompose信息
readonly dockerComposeUrl="http://heyige.cn/root/soft/-/raw/master/docker-compose-Linux-x86_64"
readonly dockerComposeLocation="/usr/local/bin/docker-compose"

# ---------指定Redis信息
readonly redisVersion="redis-7.0.12"
readonly redisBaseUrl="${redisVersion}.tar.gz"
readonly redisUrl="https://download.redis.io/releases/${redisBaseUrl}"

# 指定mongoDb信息
readonly mongodbVersion="mongodb-linux-x86_64-ubuntu2004-5.0.20"
readonly mongoDbBaseUrl="mongodb-linux-x86_64-ubuntu2004-5.0.20.tgz"
readonly mongoDbUrl="https://fastdl.mongodb.org/linux/${mongoDbBaseUrl}"

# 指定nacos信息
readonly nacosTar="nacos-server-1.4.3.tar.gz"

# 指定RocketMQ信息
readonly rockerZip="rocketmq-all-5.1.1-bin-release"

# 指定dashboard信息
readonly rockerDashboard="rocketmq-dashboard-release-1.0.0"
# naveServer地址，ip:端口，多个之间用分号隔开
readonly naveServer="192.168.152.129:9876"

# 安装MySQL
CheckAndDownLoadMysql() {
  local mysqlFile=$resLocationFile/mysql
  local mysqlCommunityServer="mysql-community-server mysql-community-server"
  # 将要注释掉的行保存到变量中
  local line_to_comment="bind-address"
  local server="mysql"
  local mysqlEditFile="/etc/mysql/mysql.conf.d/mysqld.cnf"
  mkdir -p $mysqlFile
  if test "$(systemctl is-active $server)" = "inactive"; then
    echo "mysql is not running~begin to download"
    # 下载mysql
    echo "downloading...mysql"
    wget -P $resLocationPackage $mysqlUrl
    echo "open mysql"
    # 解压mysql
    tar -xf $resLocationPackage/$mysqlBaseVersion -C $mysqlFile
    cd $mysqlFile || echo "no $mysqlFile dir "
    #  设置密码
    echo "$mysqlCommunityServer/root-pass password $root_password" | debconf-set-selections
    echo "$mysqlCommunityServer/re-root-pass password $root_password" | debconf-set-selections
    FixMysqlDb
    # 修改配置文件允许远程登录
    sed -i "s/^$line_to_comment/#$line_to_comment/" /$mysqlEditFile
    service mysql restart
    ExecMysqlCmd
  else
    echo "skip--->mysql is installed"
  fi
}

# 处理MySql依赖
FixMysqlDb() {
  dpkg -i mysql-common_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i mysql-community-client_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i mysql-client_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i mysql-community-server_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i mysql-server_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi
  echo "MySQL is done！"
}

# 执行mysql远程登录命令
ExecMysqlCmd() {
  # 执行修改语句
  mysql -u root -e "UPDATE mysql.user SET host='%' WHERE user='root' AND host='localhost';"
  # todo:这有个bug 需要手动执行
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  read -t 10 -p  "please exec:==>ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '$root_password';"|| true
  $REPLY
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  mysql -u root -e "ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '$root_password';"
  echo "MySQL Action Ok！"
}

# 下载JDK1.8
CheckAndDownLoadJDK1_8() {
  wget -P${resLocationPackage} ${jdk8Url}
#   解压jdk8
  tar -xf $resLocationPackage/$jdk1_8BaseVersionSuffix -C $resLocationFile
  cd $resLocationFile/java-se-8u41-ri  || echo "no $resLocationFile'/'java-se-8u41-ri  dir "
  local JDKBin
  JDKBin=$(pwd)
  #设置环境变量
  echo "export JAVA8_HOME=$JDKBin" >>/etc/profile
  echo "export PATH=\$PATH:\$JAVA8_HOME/bin" >>/etc/profile
  source /etc/profile
  # 验证是否安装成功
  "${JDKBin}"/java --version
}

# 下载JDK11
CheckAndDownLoadJDK11() {
  echo "downloading...jdk11"
  wget -P${resLocationPackage} ${jdk11Url}
  # 解压jdk11
  tar -xf $resLocationPackage/$jdk11BaseVersion -C $resLocationFile
  cd $resLocationFile/$JDKVersion || echo "no $resLocationFile'/'$JDKVersion dir "
  echo "open jdk11"
  local JDKBin
  JDKBin=$(pwd)
  #设置环境变量
  echo "export JAVA_HOME=$JDKBin" >>/etc/profile
  echo "export PATH=\$PATH:\$JAVA_HOME/bin" >>/etc/profile
  source /etc/profile
  # 验证是否安装成功
  java --version
}

# 下载Maven
CheckAndDownLoadMaven() {
  expect -c "
    spawn scp -o StrictHostKeyChecking=no $remoteMachine:$remoteFileLocation/$mavenVersion  $resLocationPackage
    expect \"*assword:\"
    send \"$remotePasswd\\r\"
    expect eof
  "
  mkdir -p $resLocationFile
  tar -xf $resLocationPackage/$mavenVersion -C $resLocationFile
  local mavenBin
  mavenBin=$resLocationFile/maven/bin
  export PATH=$resLocationFile/maven/bin:$PATH
  echo "export PATH=\$PATH:\$MAVEN_HOME" >>/etc/profile
  source /etc/profile
  # 验证是否安装成功
  mvn --version
  source /etc/profile

}

# TODO:从Docker安装Jenkins还是直接下载？
CheckAndDownLoadJenkins() {
  echo "jenkins"
}

# Docker
CheckAndDownLoadDocker() {
  local dockerFile=$resLocationFile/docker
  mkdir -p $dockerFile
  wget -P $dockerFile $dockerContainerd
  wget -P $dockerFile $dockerCeCli
  wget -P $dockerFile $dockerCe
  cd $dockerFile || echo "no $dockerFile dir "
  FixDockerCe
  addDockerConfig
  docker --version
}

# 处理Docker依赖
FixDockerCe() {
  dpkg -i containerd.io_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i docker-ce-cli_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi

  dpkg -i docker-ce_*.deb
  if [ $? -ne 0 ]; then
    apt-get -y -f install
  fi
  echo "Docker安装完成！"
}

# docker添加docker源
addDockerConfig() {
  if [ ! -d "/etc/docker" ]; then
    sudo mkdir -p /etc/docker
  fi
  if [ ! -f "/etc/docker/daemon.json" ]; then
    sudo touch /etc/docker/daemon.json
  fi
  # 写入配置内容到文件
  echo "{
  \"registry-mirrors\": [\"${dockerConfigUrl}\"]
}" | sudo tee /etc/docker/daemon.json
  sudo systemctl restart docker
}

# DockerCompose
CheckAndDownLoadDockerCompose() {
  touch $dockerComposeLocation
  curl -L ${dockerComposeUrl} >${dockerComposeLocation}
  chmod 777 ${dockerComposeLocation}
  docker-compose --version
}

# Redis
CheckAndDownLoadRedis() {
  wget -P $resLocationPackage $redisUrl
  echo "open redis"
  # 解压redis
  tar -xf $resLocationPackage/$redisBaseUrl -C $resLocationFile
  cd $resLocationFile/${redisVersion} || echo "no $resLocationFile/${redisVersion} dir "
  # 编译安装
  make install
  redis-server --version
}

# MongoDB
CheckAndDownLoadMongoDB() {
  echo "downLoading...mongodb"
  wget -P $resLocationPackage $mongoDbUrl
  echo "open mongodb"
  # 解压mongodb
  tar -xf $resLocationPackage/$mongoDbBaseUrl -C $resLocationFile
  cd $resLocationFile/$mongodbVersion || echo "no $resLocationFile/$mongodbVersion dir "
  local mongoBin
  mongoBin=$(pwd)
  #设置环境变量
  echo "export MONGODB_HOME=$mongoBin" >>/etc/profile
  echo "export PATH=\$PATH:\$MONGODB_HOME/bin" >>/etc/profile
  source /etc/profile
  # 创建数据库文件夹
  sudo mkdir -pv ./mongo/data/{mongodb_data,mongodb_log}
  touch ./mongo/data/mongodb_log/mongodb.log
  # 定义配置文件路径
  local config_file="$mongoBin/mongodb.conf"
  # 写入配置内容到文件
  {
    echo "port=27017"
    echo "dbpath=$mongoBin/mongo/data/mongodb_data/"
    echo "logpath=$mongoBin/mongo/data/mongodb_log/mongodb.log"
    echo "fork=true"
    echo "logappend=true"
    echo "noauth=true"
  } >>"${config_file}"
  mongod --config "${mongoBin}"/mongodb.conf
  echo "mongodb is done!"
}

# Nacos
CheckAndDownLoadNacos() {
  local nacosFile="$resLocationFile/nacos"
  mkdir -p "$nacosFile"
  # 执行 scp 并自动输入密码
  expect -c "
    spawn scp -o StrictHostKeyChecking=no $remoteMachine:$remoteFileLocation/$nacosTar $resLocationPackage
    expect \"*assword:\"
    send \"$remotePasswd\\r\"
    expect eof
  "
  echo "open nacos"
  # 解压 nacos
  tar -xf $resLocationPackage/$nacosTar -C $resLocationFile
  cd "$nacosFile" || echo "no $nacosFile dir "
  # 启动 nacos
  # 使用集群需额外配置~
  source /etc/profile
  $nacosFile/bin/startup.sh -m standalone
}

# RocketMQ
# todo: to run have a bug ?
CheckAndDownLoadRocketMQ() {
  local runMqSh=$resLocationFile/$rockerZip/start-rocket.sh
  expect -c "
    spawn scp -o StrictHostKeyChecking=no $remoteMachine:$remoteFileLocation/$rockerZip.zip $resLocationPackage
    expect \"*assword:\"
    send \"$remotePasswd\\r\"
    expect eof
  "
  touch $runMqSh
  unzip $resLocationPackage/$rockerZip.zip  -d $resLocationFile/$rockerZip
  echo "nohup sh $resLocationFile/$rockerZip/$rockerZip/bin/mqnamesrv &" >$runMqSh
  echo "nohup sh $resLocationFile/$rockerZip/$rockerZip/bin/mqbroker -n localhost:9876 &" >>$runMqSh
  chmod 777 $runMqSh
  . ${runMqSh}
  ps -ef | grep mqnamesrv
  jps

}

# RocketMQDashboard
CheckAndDownLoadRocketMQDashboard() {

  expect -c "
    spawn scp -o StrictHostKeyChecking=no $remoteMachine:$remoteFileLocation/$rockerDashboard.zip  $resLocationPackage
    expect \"*assword:\"
    send \"$remotePasswd\\r\"
    expect eof
  "
  unzip $resLocationPackage/$rockerDashboard.zip -d $resLocationFile
  cd $resLocationFile/$rockerDashboard || echo "no $resLocationFile/$rockerDashboard dir "
  local mqDashboardBin
  mqDashboardBin=$(pwd)
  cd "${mqDashboardBin}"/src/main/resources/ || echo "no $mqDashboardBin/src/main/resources/  dir "
  sed -i "s/rocketmq\.config\.namesrvAddr=.*/rocketmq.config.namesrvAddr=${naveServer}/" application.properties
  cd "${mqDashboardBin}" || echo "no $mqDashboardBin dir "
  mvn clean package -Dmaven.test.skip=true
  # todo:如果target不存在则执行进入 mvn clean package -Dmaven.test.skip=true,不然直接进入tar启动 java -jar rocketmq-dashboard-1.0.0.jar
  # 默认8080端口
  cd target || echo "no $mqDashboardBin/target dir "
  java -jar rocketmq-dashboard-1.0.0.jar

}

# 卸载 unattended-upgrades 软件包自动升级工具
uninstallUnattendedUpgrades() {
  local PID
  PID=$(pgrep unattended-upgrades)
  if [ -n "$PID" ]; then
    echo "find  unattended-upgrades process，PID: $PID"
    echo "killing--> ${PID}"
    sudo kill -9 "$PID"
    echo "kill finished!"
  fi

  # 卸载 unattended-upgrades 软件包
  echo "begin uninstall unattended-upgrades software"
  sudo apt-get remove -y unattended-upgrades
  echo "uninstall finished!"
}

# 初始化---安装工具
installUtil() {
  mkdir -p $resLocationPackage
  mkdir -p $resLocationFile
  apt -y install unzip
  apt install -y expect
  # GCC依赖
  apt install -y build-essential
  apt install -y gcc-9 g++-9 gcc-10 g++-10
  apt install -y make
  uninstallUnattendedUpgrades

}

# main函数
main() {

  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is init~~~~~~~~~~~~~"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  installUtil

  # 1.mysql执行下载解压设置环境变量
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading mysql"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadMysql

  # 1.下载配置 jdk1.8&11
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading JDK8"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadJDK1_8

  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading JDK11"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadJDK11


  #   3.下载配置  maven
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading maven"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadMaven

  # 4.下载配置  docker
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading docker"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadDocker

  # 5.下载配置  docker-compose
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading docker-compose"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadDockerCompose

  # 6.下载配置  Redis
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo    "now is downloading Redis"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadRedis

  # 7.下载配置  MongoDB
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo    "now is downloading MongoDB"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  CheckAndDownLoadMongoDB
  sleep 1

  #  8.下载配置  Nacos
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo    "now is downloading Nacos"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadNacos

  # 9.下载配置  RocketMQ
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading RocketMQ"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadRocketMQ

  #  10.下载配置  RocketMQDashboard
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  echo "now is downloading RocketMQDashboard"
  echo -e "\e[31m============================================================================================================================================================\e[0m"
  sleep 1
  CheckAndDownLoadRocketMQDashboard

}

main
